package com.ncloud.msg.business;

import com.alibaba.fastjson.JSONObject;
import com.ncloud.msg.entity.Email;
import com.ncloud.msg.entity.EmailConfig;
import com.ncloud.msg.service.MailService;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.internet.MimeMessage;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.List;

/**
 * Created by shiqiang on 2017/5/15.
 */
@Service
public class EmailBusi {
    @Autowired
    private MailService mailService;
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Autowired
    private EmailConfig eMailConfig;
    @Transactional(isolation = Isolation.SERIALIZABLE)
    public void SendMail(){
        final MimeMessage mimeMessage = mailSender.createMimeMessage();

       List<Email> list =  mailService.getEmails("0",10);
       for(Email email : list){
           sendEmailOne(email,mimeMessage);
       }
    }
    @Transactional
    public void moveEmailToHis(){
        List<Email> list =  mailService.getEmails("2",100);
        for(Email email : list){
            mailService.insertEmailHistory(email.getMsgId());
            mailService.deleteEmail(email.getMsgId());
        }
    }

    private void sendEmailOne(Email email, MimeMessage mimeMessage){
        try {
            final MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setFrom(eMailConfig.getEmailFrom());
            message.setTo(email.getMsgTo().split(";"));
            message.setSubject(email.getSubject());
            if(email.getCc()!=null){
                message.setCc(email.getCc().split(";"));
            }
            if(email.getBcc()!=null){
                message.setBcc(email.getBcc().split(";"));
            }
             /*  if(email.getAttach()!=null){
               }*/
             /*模板特殊处理*/
            if("1".equals(email.getMsgType()) && !StringUtils.isEmpty(email.getTemplateName())){
                String jsonParam = email.getContent();
                // 在模板文件目录中寻找名称为name的模板文件
                Template template = freeMarkerConfigurer.getConfiguration().getTemplate(email.getTemplateName());
                String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, JSONObject.parse(jsonParam));
                message.setText(html,true);
            }else{
                message.setText(email.getContent());
            }

              /*附件暂时不处理*/
            String attach = email.getAttach();
            //发送邮件
            mailSender.send(mimeMessage);

            /*更新记录*/
            email.setMsgCode("2");
            email.setMsgResult("发送成功");
            mailService.updateEmail(email);

        }catch (Exception e){
            ByteArrayOutputStream buf = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(buf, true));
            String error = buf.toString();
            error = error.length() > 2000 ? error.substring(0,2000):error;
            email.setMsgException(error);
            email.setMsgResult(e.getMessage().length()>200 ? e.getMessage().substring(0,200):e.getMessage());
            email.setMsgCode("9");
            mailService.updateEmail(email);
        }
    }
}
